package cn.dankal.basiclib.common.qiniu.upload;

import android.Manifest;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;

import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import cn.dankal.basiclib.base.callback.DKCallBackBoolean;
import cn.dankal.basiclib.util.FileUtil;
import cn.dankal.basiclib.util.image.ImagePathUtil;

import static android.app.Activity.RESULT_OK;

/**
 * description: 上传图片工具类
 * <p>
 * Edit by Vane
 *
 * @author fred
 * @since 2018/8/2.
 */

public class UploadPic implements IUploadPic {

    public static final int TAKE_PHOTO = 1001;
    public static final int PICK_PHOTO = 1002;

    private WeakReference<AppCompatActivity> mActivity;
    private Context mContext;
    private UploadManager uploadManager;
    private List<File> uploadFiles = new ArrayList<>();
    private String[] uploadKeys;
    private volatile boolean isCancelled = false;

    private Uri takePhotoUri;

    public UploadPic(AppCompatActivity activity) {
        mActivity = new WeakReference<>(activity);
        mContext = activity.getApplicationContext();
        uploadManager = new UploadManager();
    }

    @Override
    public void checkPermission(DKCallBackBoolean callBack) {
        AppCompatActivity activity = mActivity.get();
        RxPermissions rxPermissions = new RxPermissions(activity);
        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .subscribe(granted -> callBack.action(granted ? DKCallBackBoolean.YES : DKCallBackBoolean.NO));
    }

    @Override
    public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) return false;

        try {
            if (TAKE_PHOTO == requestCode) {
                File takePhotoFile = FileUtil.compressImageUriToFile(mContext, takePhotoUri);
                uploadFiles.add(takePhotoFile);
            } else if (PICK_PHOTO == requestCode) {
                Uri pickPhotoUri = Uri.parse(ImagePathUtil.getImageAbsolutePath(mActivity.get(), data.getData()));
                File pickPhotoFile = FileUtil.compressImageUriToFile(mContext, pickPhotoUri);
                uploadFiles.add(pickPhotoFile);
            }
        } catch (Exception ignored) {
            return false;
        }
        return true;
    }

    public void uploadImg(DKCallBackBoolean dkCallBack, String qiniuToken) {
        uploadKeys = new String[uploadFiles.size()];
        uploadImg(uploadFiles, 0, dkCallBack, qiniuToken);
    }


    private void uploadImg(List<File> files, int index, DKCallBackBoolean dkCallBack, String qiniuToken) {
        String fileName = "cheersto-" + System.currentTimeMillis() + "-" + new Random().nextInt(1000) + ".jpg";

        if (index == files.size()) {
            dkCallBack.action(DKCallBackBoolean.YES);
        } else {
            uploadManager.put(files.get(index), fileName, qiniuToken, (key, info, response) -> {
                if (info.isOK()) {
                    int fileCount = index;
                    uploadKeys[fileCount] = key;
                    FileUtil.deleteFile(files.get(fileCount));
                    uploadImg(files, ++fileCount, dkCallBack, qiniuToken);
                } else {
                    uploadKeys = null;
                    dkCallBack.action(DKCallBackBoolean.NO);
                    Log.e("Qiniu", "uploadIdcardImg: " + info.toString());
                }
            }, new UploadOptions(null, null, false, null,
                    () -> isCancelled));
        }
    }

    public void clear() {
        if (uploadFiles != null) uploadFiles.clear();
        if (uploadKeys != null) uploadKeys = null;
    }

    public void remove(int pos) {
        try {
            FileUtil.deleteFile(uploadFiles.get(pos));
            uploadFiles.remove(pos);
            uploadKeys[pos] = null;
        } catch (Exception ignore) {
        }
    }

    public List<File> getUploadFiles() {
        return uploadFiles;
    }

    public String[] getUploadKeys() {
        return uploadKeys;
    }


    /**
     * 释放资源
     */
    public void release() {
        try {
            for (int i = 0; i < uploadFiles.size(); i++) {
                FileUtil.deleteFile(uploadFiles.get(i));
            }
        } catch (Exception ignore) {

        }
        isCancelled = true;
        uploadManager = null;
        mActivity = null;
        clear();
        uploadFiles = null;
    }


    /**
     * 拍照
     */
    public void takePhoto() {
        final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        String photoName = FileUtil.getFileNameByTime("IMG", "jpg");
        final File tempFile = new File(FileUtil.CAMERA_PHOTO_DIR, photoName);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            final ContentValues contentValues = new ContentValues(1);
            contentValues.put(MediaStore.Images.Media.DATA, tempFile.getPath());
            final Uri uri = mContext.getContentResolver().
                    insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            final File realFile = FileUtil.getFileByPath(FileUtil.getRealFilePath(mContext, uri));
            final Uri realUri = Uri.fromFile(realFile);
            takePhotoUri = realUri;
            intent.putExtra(MediaStore.EXTRA_OUTPUT, realUri);
        } else {
            final Uri fileUri = Uri.fromFile(tempFile);
            takePhotoUri = fileUri;
            intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        }
        if (mActivity.get() != null) {
            mActivity.get().startActivityForResult(intent, TAKE_PHOTO);
        }
    }

    /**
     * 从相册获取图片
     */
    public void pickPhoto() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        if (mActivity.get() != null) {
            mActivity.get().startActivityForResult(Intent.createChooser(intent, "选择图片获取方式"), PICK_PHOTO);
        }
    }
}
